/* ****************************************************************************
utilities.h
-------------------------------------------------------------------------------

Copyright (c) 2017, Tain L.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

**************************************************************************** */

#if !defined(SPEARS_ASSET_MANAGER_H)
#define SPEARS_ASSET_MANAGER_H

#include "my-prerequisites.h"
#include "atscene.h"

namespace Spears
{
	namespace Asset
	{
		class Utilities
		{
		public:
			static std::unique_ptr<atScene> load_asset(const std::string& filename);
		
		protected:
			static void load_transform(atTransform& transform, const nlohmann::json& j_transform);
			static atNode* load_scene_tree(const nlohmann::json& j_root);
			static atColor load_color(const nlohmann::json& j_color);
			static void load_material(atMaterial& material, const nlohmann::json& j_material);

		public:
		};

		inline void Utilities::load_transform(atTransform& transform, const nlohmann::json& j_transform)
		{
			using json = nlohmann::json;

			if (j_transform.is_object())
			{
				json j_matrix = j_transform["matrix"];
				for (int n = 0; n < 4; ++n)
				{
					for (int m = 0; m < 4; ++m)
					{
						transform.m_matrix.data[m][n] = j_matrix[m + 4 * n];
					}
				}
			}
		}

		inline atColor Utilities::load_color(const nlohmann::json& j_color)
		{
			using json = nlohmann::json;
			atColor clr;

			if (j_color.is_array() && j_color.size() >=4)
			{
				clr.a = j_color[0];
				clr.r = j_color[1];
				clr.g = j_color[2];
				clr.b = j_color[3];
			}

			return clr;
		}

		inline void Utilities::load_material(atMaterial& material, const nlohmann::json& j_material)
		{
			using json = nlohmann::json;

			material.clear();
			std::string	jname = j_material["name"];
			material.set(atMaterial::KEY_NAME, jname);

			std::string	jsd = j_material["shading_model"];
			material.set(atMaterial::SHADING_MODEL, jsd);

			if ("phong" == jsd)
			{
				material.set(atMaterial::CLR_DIFFUSE, load_color(j_material["clr_diffuse"]));
				material.set(atMaterial::CLR_SPECULAR, load_color(j_material["clr_specular"]));
				material.set(atMaterial::CLR_AMBIENT, load_color(j_material["clr_ambient"]));
				material.set(atMaterial::CLR_EMISSIVE, load_color(j_material["clr_emissive"]));
			}
		}

		inline atNode* Utilities::load_scene_tree(const nlohmann::json& j_root)
		{
			using json = nlohmann::json;

			atNode* p_node = new atNode();

			json::const_iterator citer_meshes = j_root.find("mesh_indices");
			if (citer_meshes != j_root.end())
			{
				for (size_t i = 0; i < citer_meshes->size(); ++i)
				{
					p_node->m_meshes.push_back((*citer_meshes)[i]);
				}
			}

			load_transform(p_node->m_transform, j_root["transform"]);

			json::const_iterator citer_children = j_root.find("children");
			if (citer_children != j_root.end())
			{
				for (auto& j_child : *citer_children)
				{
					atNode* p_child = load_scene_tree(j_child);
					if (nullptr != p_child)
					{
						p_node->m_children.push_back(p_child);
					}
				}
			}
			return p_node;
		}

		inline std::unique_ptr<atScene> Utilities::load_asset(const std::string& filename)
		{
			using json = nlohmann::json;
			std::unique_ptr<atScene> p_ret(new atScene);

			try
			{
				std::ifstream input(filename);
				if (true != input.is_open())
					throw std::exception("failed to open the asset file.");

				json j_root;
				input >> j_root;

				for (const auto& j_material : j_root["materials"])
				{
					atMaterial* p_tmp_material = new atMaterial;
					if(nullptr != p_tmp_material)
					{
						load_material(*p_tmp_material, j_material);
						p_ret->manage_material(p_tmp_material);
					}
				}

				for (const auto& j_light : j_root["lights"])
				{
					atLight* p_tmp_light = new atLight;
					p_tmp_light->m_type = atLight::_string_to_type(j_light["type"]);

					p_tmp_light->m_ambient.a = j_light["color_ambient"][0];
					p_tmp_light->m_ambient.r = j_light["color_ambient"][1];
					p_tmp_light->m_ambient.g = j_light["color_ambient"][2];
					p_tmp_light->m_ambient.b = j_light["color_ambient"][3];

					p_tmp_light->m_specular.a = j_light["color_specular"][0];
					p_tmp_light->m_specular.r = j_light["color_specular"][1];
					p_tmp_light->m_specular.g = j_light["color_specular"][2];
					p_tmp_light->m_specular.b = j_light["color_specular"][3];

					p_tmp_light->m_diffuse.a = j_light["color_diffuse"][0];
					p_tmp_light->m_diffuse.r = j_light["color_diffuse"][1];
					p_tmp_light->m_diffuse.g = j_light["color_diffuse"][2];
					p_tmp_light->m_diffuse.b = j_light["color_diffuse"][3];

					p_tmp_light->m_angle_inner_cone = j_light["angle_inner_cone"];
					p_tmp_light->m_angle_outer_cone = j_light["angle_outer_cone"];

					p_tmp_light->m_attenuation_constant = j_light["att_constant"];
					p_tmp_light->m_attenuation_linear = j_light["att_linear"];
					p_tmp_light->m_attenuation_quadratic = j_light["att_quadratic"];

					p_tmp_light->m_position.x = j_light["pos"][0];
					p_tmp_light->m_position.y = j_light["pos"][1];
					p_tmp_light->m_position.z = j_light["pos"][2];

					p_tmp_light->m_direction.x = j_light["dir"][0];
					p_tmp_light->m_direction.y = j_light["dir"][1];
					p_tmp_light->m_direction.z = j_light["dir"][2];

					p_tmp_light->m_up.x = j_light["up"][0];
					p_tmp_light->m_up.y = j_light["up"][1];
					p_tmp_light->m_up.z = j_light["up"][2];

					p_ret->manage_light(p_tmp_light);
				}

				for (const auto& j_mesh : j_root["meshes"])
				{
					atMesh* p_tmp_mesh = new atMesh;

					for (const auto& j_vtx : j_mesh["vertices"])
					{
						atPoint	vtx;
						vtx.x = j_vtx[0];
						vtx.y = j_vtx[1];
						vtx.z = j_vtx[2];
						p_tmp_mesh->m_vertices.push_back(vtx);
					}

					for (const auto& j_nml : j_mesh["normals"])
					{
						atNormal nml;
						nml.x = j_nml[0];
						nml.y = j_nml[1];
						nml.z = j_nml[2];
						p_tmp_mesh->m_normals.push_back(nml);
					}

					for (const auto& j_face : j_mesh["faces"])
					{
						atFace face;
						face.v1 = j_face[0];
						face.v2 = j_face[1];
						face.v3 = j_face[2];
						p_tmp_mesh->m_faces.push_back(face);
					}

					p_tmp_mesh->m_material_index = j_mesh["material"];

					p_ret->manage_mesh(p_tmp_mesh);
				}

				atNode* p_scene_root = load_scene_tree(j_root["scene_tree"]);
				if (nullptr != p_scene_root)
				{
					p_ret->manage_scene_tree(p_scene_root);
				}
			}
			catch (std::exception ex)
			{
				throw ex;
			}

			return std::move(p_ret);
		}
	} // namespace Asset
} //namespace Spears

#endif // SPEARS_ASSET_MANAGER_H